<!-- 添加企业 编辑企业 -->
<script setup lang='ts' name="org-role-add">
import type { FormInstance } from 'element-plus'

import { getOcrIdCard } from '@fl/api/anjutong'
import { addCompanyOrg, addOrgUserForIam, getAllCompanyOrg, getNewCompanyOrgDetail, getOrgDictInfo, registerCompanyAdminUser, useGetCatTypeDictInfo } from '@fl/api/iam-api'
import { getAllRegionList } from '@fl/api/xf-api'
import Address from '@fl/components/address.vue'
import FlUpload from '@fl/components/fl-upload.vue'
import { useUserStore } from '@fl/store/modules/user'
import { formatTime, readFileAsBase64 } from '@fl/utils'
import { ElButton, ElCard, ElCol, ElDatePicker, ElForm, ElFormItem, ElInput, ElMessage, ElOption, ElRadio, ElRadioGroup, ElRow, ElSelect, ElSwitch } from 'element-plus'
import { ref, watch } from 'vue'
import { useRoute, useRouter } from 'vue-router'

import { CAT_TYPE } from '../constant'
import { useDicts } from '../hooks/use-dicts'
import { useForm } from './hooks/use-form'
import { useRule } from './hooks/use-rule'
import { useDicts as useDicts2 } from '@fl/pages/contract-management/hooks/use-dicts'

const userStore = useUserStore()
const { go } = useRouter()
const { rules } = useRule()

const { dicts: { CooperationType, EnterpriseRank } } = useDicts()
const { form } = useForm()
const router = useRouter()
const route = useRoute()
const formRef = ref()
const dueDate = ref<any>({})
const loading = ref<boolean>(false)
const isEdit = ref<boolean>(false)
const isLoading = ref<boolean>(true)
const canUpdateCode = ref<boolean>(false) // 信用代码为空时可编辑

const cityList = ref([]) // 城市列表
function queryCityList() {
    getAllRegionList().then((res) => {
        const dataList = res.data
        cityList.value = dataList
    })
}

function selectCityChange(val) {
    if (val) {
        const cityItem = cityList.value.find((item) => {
            return item?.areaCode === val
        })
        form.areaName = cityItem.areaName
        form.shortAreaCode = cityItem.extAreaCode
    }
    else {
        form.areaCode = ''
        form.areaName = ''
        form.shortAreaCode = ''
    }
}

const orgs = ref<any>([])
const orgTypeOptions = ref<any>([])
const { data: CatType } = useGetCatTypeDictInfo()
const { dicts: { PlatType } } = useDicts2()

async function doSave(formEl: FormInstance | undefined) {
    if (!formEl)
        return
    await formEl.validate((valid, fields) => {
        if (valid)
            saveData()
        else
            console.log('error!', fields)
    })
}

async function saveData() {
    const {
        areaCode, // 所属城市code
        areaName, // 所属城市名称
        businessLicense,
        catTypeId, // 业务类别
        cooperationType, // 合作类别
        contractFlag, // 是否开通电子签
        contractPlat, // 电子签平台 1:诺诺；2:E签宝
        email, // 联系人邮箱
        enterpriseId, // 企业id
        enterpriseLevel,
        enterpriseLevelId,
        enterpriseName, // 公司名称
        enterpriseShort, // 公司简称
        enterpriseType,
        establishmenDate,
        idCard, // 联系人身份证
        legalCard,
        legalCardBack, // 企业法人身份证（反）
        legalCardFront, // 企业法人身份证（正）
        legalRepresentative, // 企业法人
        parentId,
        parentName,
        phonenumber, // 联系人手机号
        registeredAddress, // 企业注册地
        registeredMobile, // 企业联系电话
        shangjqyId,
        shortAreaCode,
        status, // 企业状态
        unifiedSocialCreditCode, // 统一信用代码
        userName, // 联系人姓名
    } = form

    console.log('save前', form)
    const data: any = {
        areaCode,
        areaName,
        businessLicense,
        catTypeId: catTypeId.sort().join(','),
        cooperationType,
        contractFlag,
        contractPlat,
        email,
        enterpriseAccount: 10000, // 固定 10000
        enterpriseId,
        enterpriseLevel,
        enterpriseLevelId,
        enterpriseName,
        enterpriseShort,
        enterpriseType,
        establishmenDate: formatTime(establishmenDate, 'yyyy-MM-dd HH:mm:ss'),
        idCard,
        legalCard,
        legalCardBack,
        legalCardFront,
        legalRepresentative,
        parentId: enterpriseLevelId === '1' ? '' : parentId,
        parentName,
        phonenumber,
        registeredAddress,
        registeredMobile,
        shortAreaCode,
        shangjqyId,
        status,
        unifiedSocialCreditCode,
        userName,
    }

    // 编辑必传
    if (isEdit.value)
        data.id = form.id

    sendFlow(data)
}

function sendFlow(data: any) {
    console.log('保存', data)
    data.createBy = userStore.getUserInfo?.id
    data.createdName = userStore.getUserInfo?.name
    const cityItem = cityList.value.find(item => item?.areaCode === data.areaCode)
    const shortAreaCode = cityItem?.extAreaCode || ''
    data.shortAreaCode = shortAreaCode
    addCompanyOrg(data).then(async (res: any) => {
        console.log('res', res)
        if (res?.code === 200) {
            canUpdateCode.value = false
            ElMessage.success('保存成功')
            
            // 新增
            if (!form?.id) {
                const hasIamBusiness = form.catTypeId.some(tId => ['9', '10'].includes(tId)) // 9适老化、10电梯加装
                if (form.catTypeId.includes('2')) { // 好房
                    registerCompanyAdminUser({
                        companyId: res.data.DataId, // 对应企业保存接口返回的DataId
                        userid: res.data.loginCode, // 对应企业保存接口返回的loginCode
                        tyxydm: data.unifiedSocialCreditCode, // 统一信用代码
                        areaCode: data.areaCode, // 城市code
                        areaName: data.areaName, // 城市名称
                        shortAreaCode: data.shortAreaCode, // 城市简化code
                        userName: data.userName, // 填写的姓名
                        phone: data.phonenumber, // 填写的手机号码
                        companyName: data.enterpriseName, // 企业名
                    }).then((result) => {
                        if (result?.code === 200) {
                            // ElMessage.success(result.msg)
                        }
                        else {
                            ElMessage.warning(result.msg)
                        }
                    })
                } else if (hasIamBusiness) {
                    addOrgUserForIam({
                        isEdit: false,
                        params: {
                            scope: data.shortAreaCode,
                            userName: `${res.data.loginCode}-${data.enterpriseAccount}`
                        },
                    }).then((result) => {
                        if (result?.code === 200) {
                            // ElMessage.success(result.msg)
                        }
                        else {
                            ElMessage.error(result.msg)
                        }
                    })
                }
            }

            setTimeout(() => {
                goToList()
            }, 1000)
        }
        else {
            ElMessage({ message: res.msg, type: 'error' })
        }
    }).catch((err) => {
        const message = err?.response?.data?.message || err
        ElMessage({ message, type: 'error' })
    })
}

function enterpriseLevelChange(val: any) {
    if (val === '1') {
        form.parentId = form.enterpriseName
        form.enterpriseLevel = '一级企业'
        form.parentName = ''
        // rules.parentId = [
        //     { message: '', required: false, trigger: 'change' },
        // ]
    }
    else {
        form.parentId = ''
        form.enterpriseLevel = '二级企业'
        // rules.parentId = [
        //     { message: '请选择上级', required: true, trigger: 'change' },
        // ]
    }
}

function catTypeIdChange(val: any) {
    if (!val.includes(CAT_TYPE['租赁业务'])) {
        form.cooperationType = ''
        rules.cooperationType = [
            { message: '请选择', required: false, trigger: 'change' },
        ]
    }
    else {
        rules.cooperationType = [
            { message: '请选择', required: true, trigger: 'change' },
        ]
    }
}

// 选择上级企业
function parentIdChange(val: any) {
    // console.log('上级', val, orgs.value)
    const target = orgs.value.find((v: any) => v.value === val)
    console.log('parentIdChange', target.enterpriseObjectID)
    form.shangjqyId = target.enterpriseObjectID
    form.parentName = target.label
}

function legalCardFrontChange() {
    formRef.value.clearValidate('legalCardFront')
}

async function getDueDate({ file }) {
    const image = await readFileAsBase64(file)
    getOcrIdCard({ image }).then((res: any) => {
        const { front_result } = res.data.data.results

        if (!front_result?.有效期限) {
            ElMessage.error('请上传企业法人身份证(反面)!')
            form.legalCardBack = ''
            dueDate.value = {
                end: '',
                start: '',
            }
            return
        }

        dueDateDefault(front_result)
    }).catch((error: any) => {
        console.error(error)
    })
}

function dueDateDefault(date: any) {
    const [start, end] = date.有效期限.split('-')
    dueDate.value = {
        end: day(end).format('YYYY年MM月DD日'),
        start: day(start).format('YYYY年MM月DD日'),
    }
    formRef.value.clearValidate('legalCardBack')
}

// 使用企业法人信息
function useLegalInfo() {
    form.idCard = form.legalCard
    if (form.legalRepresentative) {
        form.userName = form.legalRepresentative
        formRef.value.clearValidate('userName')
    }
    if (form.registeredMobile) {
        form.phonenumber = form.registeredMobile
        formRef.value.clearValidate('phonenumber')
    }
}

function goToList() {
    router.replace('/business-management/company-org')
}

function goback() {
    canUpdateCode.value = false
    go(-1)
}

function init(val: any) {
    const id = val.query?.id
    isEdit.value = !!id
    console.log('init', val)

    // 所有公司列表
    getAllCompanyOrg({ page: 1, size: 9999 }).then((res: any) => {
        const data = res?.data ?? []
        data.forEach((v: any) => {
            if (v.enterpriseId) {
                orgs.value.push({
                    ...v,
                    label: v.enterpriseName,
                    value: v.enterpriseId,
                })
            }
        })
    })

    // 企业类型
    getOrgDictInfo().then((res: any) => {
        if (res.code === 200) {
            console.log('企业类型', res.data)
            orgTypeOptions.value = res.data
        }
    })

    if (!isEdit.value) {
        isLoading.value = false
        return
    }

    // 详情
    getNewCompanyOrgDetail(id).then((res: any) => {
        if (res.code === 200) {
            const detail = res.data
            Object.assign(form, {
                ...detail,
                businessLicense: detail.businessLicense || '',
                catTypeId: detail.catTypeId ? detail.catTypeId.split(',') : [],
                legalCardBack: detail.legalCardBack || '',
                legalCardFront: detail.legalCardFront || '',
                parentId: detail.enterpriseLevelId === '1' ? detail.enterpriseName : detail.parentId,
                contractFlag: String(detail.contractFlag),
                contractPlat: detail.contractPlat ? String(detail.contractPlat) : undefined,
                // unifiedSocialCreditCode: ''
            })
            isLoading.value = false
            console.log('企业详情form', form)
            canUpdateCode.value = !form.unifiedSocialCreditCode
        }
        else {
            isLoading.value = false
        }
    })
}

watch(route, (val: any) => {
    init(val)
    queryCityList()
}, {
    deep: true,
    immediate: true,
})
</script>

<template>
    <ElCard class="mb-20">
        <ElRow>
            <ElButton @click="goback">
                返回列表
            </ElButton>
        </ElRow>

        <div class="info-title">
            企业注册信息
        </div>

        <el-skeleton v-if="isLoading"
                     animated
        />

        <ElForm v-else
                ref="formRef"
                :model="form"
                label-position="top"
                label-width="auto"
                :rules="rules"
        >
            <ElRow :gutter="20">
                <ElCol :span="8">
                    <ElFormItem label="企业号"
                                prop="enterpriseId"
                    >
                        <ElInput v-model="form.enterpriseId"
                                 :disabled="true"
                        />
                    </ElFormItem>
                </ElCol>
            </ElRow>

            <ElRow :gutter="20">
                <ElCol :span="8">
                    <ElFormItem label="企业名称"
                                prop="enterpriseName"
                    >
                        <ElInput v-model="form.enterpriseName"
                                 :disabled="isEdit"
                        />
                    </ElFormItem>
                </ElCol>

                <ElCol :span="8">
                    <ElFormItem label="所在城市"
                                prop="areaCode"
                    >
                        <ElSelect v-model="form.areaCode"
                                  placeholder="请选择城市"
                                  clearable
                                  @change="selectCityChange"
                        >
                            <ElOption v-for="item in cityList"
                                      :key="item.areaCode"
                                      :value="item.areaCode"
                                      :label="item.areaName"
                            />
                        </ElSelect>
                    </ElFormItem>
                </ElCol>

                <ElCol :span="8">
                    <ElFormItem label="企业简称"
                                prop="enterpriseShort"
                    >
                        <ElInput v-model="form.enterpriseShort" />
                    </ElFormItem>
                </ElCol>
            </ElRow>

            <ElRow :gutter="20">
                <ElCol :span="8">
                    <ElFormItem label="统一社会信用代码"
                                prop="unifiedSocialCreditCode"
                    >
                        <ElInput v-model="form.unifiedSocialCreditCode"
                                 :disabled="isEdit && !canUpdateCode"
                        />
                    </ElFormItem>
                </ElCol>

                <ElCol :span="8">
                    <ElFormItem label="企业联系电话"
                                prop="registeredMobile"
                    >
                        <ElInput v-model="form.registeredMobile"
                                 maxlength="12"
                        />
                    </ElFormItem>
                </ElCol>
            </ElRow>

            <ElRow :gutter="20">
                <ElCol :span="8">
                    <ElFormItem label="企业级别"
                                prop="enterpriseLevelId"
                    >
                        <ElRadioGroup v-model="form.enterpriseLevelId"
                                      @change="enterpriseLevelChange"
                        >
                            <ElRadio v-for="item in EnterpriseRank"
                                     :key="item.value"
                                     :value="item.value"
                            >
                                {{ item.label }}
                            </ElRadio>
                        </ElRadioGroup>
                    </ElFormItem>
                </ElCol>

                <ElCol :span="8">
                    <ElFormItem label="所属上级企业"
                                prop="parentId"
                    >
                        <ElSelect v-model="form.parentId"
                                  :loading="loading"
                                  :disabled="form.enterpriseLevelId === '1'"
                                  filterable
                                  @change="parentIdChange"
                        >
                            <ElOption v-for="item in orgs"
                                      :key="item.enterpriseId"
                                      :value="item.enterpriseId"
                                      :label="item.enterpriseName"
                            />
                        </ElSelect>
                    </ElFormItem>
                </ElCol>
            </ElRow>

            <ElRow :gutter="20">
                <ElCol :span="8">
                    <ElFormItem label="业务类别"
                                prop="catTypeId"
                    >
                        <ElSelect v-model="form.catTypeId"
                                  collapse-tags
                                  collapse-tags-tooltip
                                  multiple
                                  @change="catTypeIdChange"
                        >
                            <ElOption v-for="item in CatType"
                                      :key="item.value"
                                      :value="item.value"
                                      :label="item.label"
                            />
                        </ElSelect>
                    </ElFormItem>
                </ElCol>
            </ElRow>

            <ElRow :gutter="20">
                <ElCol :span="8">
                    <ElFormItem label="合作类型"
                                prop="cooperationType"
                    >
                        <ElSelect v-model="form.cooperationType"
                                  :disabled="!form.catTypeId.includes(CAT_TYPE['租赁业务'])"
                        >
                            <ElOption v-for="item in CooperationType"
                                      :key="item.value"
                                      :value="item.value"
                                      :label="item.label"
                            />
                        </ElSelect>
                    </ElFormItem>
                </ElCol>

                <ElCol :span="8">
                    <ElFormItem label="企业类型"
                                prop="enterpriseType"
                    >
                        <ElSelect v-model="form.enterpriseType"
                                  remote
                        >
                            <ElOption v-for="item in orgTypeOptions"
                                      :key="item.dictValue"
                                      :value="item.dictValue"
                                      :label="item.dictLabel"
                            />
                        </ElSelect>
                    </ElFormItem>
                </ElCol>
            </ElRow>

            <ElRow :gutter="20">
                <ElCol :span="8">
                    <ElFormItem label="注册日期"
                                prop="establishmenDate"
                    >
                        <ElDatePicker v-model="form.establishmenDate"
                                      type="date"
                                      placeholder="请选择"
                                      style="width: 100%"
                        />
                    </ElFormItem>
                </ElCol>
            </ElRow>

            <ElRow :gutter="20">
                <ElCol :span="8">
                    <ElFormItem label="企业法人"
                                prop="legalRepresentative"
                    >
                        <ElInput v-model="form.legalRepresentative" />
                    </ElFormItem>
                </ElCol>

                <ElCol :span="8">
                    <ElFormItem label="法人证件号码"
                                prop="legalCard"
                    >
                        <ElInput v-model="form.legalCard"
                                 maxlength="18"
                        />
                    </ElFormItem>
                </ElCol>
            </ElRow>

            <ElRow :gutter="20">
                <ElCol :span="12">
                    <ElFormItem label="营业执照"
                                prop="businessLicense"
                                class="tip_box"
                    >
                        <FlUpload v-model="form.businessLicense" />
                        <!-- <div class="tips">
                            <p>有效期:</p>

                            <p>2019年08月27日 至 2049年08月27日</p>
                        </div> -->
                    </ElFormItem>
                </ElCol>
            </ElRow>

            <ElRow :gutter="20">
                <ElCol :span="12">
                    <ElFormItem label="企业法人身份证(正面)"
                                prop="legalCardFront"
                                class="tip_box"
                    >
                        <FlUpload v-model="form.legalCardFront"
                                  @success="legalCardFrontChange"
                        />
                    </ElFormItem>
                </ElCol>

                <ElCol :span="12">
                    <ElFormItem label="企业法人身份证(反面)"
                                prop="legalCardBack"
                                class="tip_box"
                    >
                        <FlUpload v-model="form.legalCardBack"
                                  @success="getDueDate"
                        />

                        <div v-if="dueDate.start"
                             class="tips"
                        >
                            <p>有效期:</p>

                            <p>{{ dueDate.start }} 至 {{ dueDate.end }}</p>
                        </div>
                    </ElFormItem>
                </ElCol>
            </ElRow>

            <ElFormItem label="企业注册地址"
                        prop="registeredAddress"
            >
                <Address v-model="form.registeredAddress" />
            </ElFormItem>

            <ElFormItem label="企业状态"
                        prop="status"
            >
                <ElSwitch v-model="form.status"
                          active-value="0"
                          inactive-value="1"
                />
            </ElFormItem>

            <ElRow :gutter="20">
                <ElCol :span="8">
                    <ElFormItem label="是否开通电子签"
                                prop="contractFlag"
                    >
                        <ElSwitch v-model="form.contractFlag"
                                  active-value="1"
                                  inactive-value="0"
                        />
                    </ElFormItem>
                </ElCol>

                <ElCol :span="8">
                    <ElFormItem label="电子签平台"
                                prop="contractPlat"
                    >
                        <ElSelect v-model="form.contractPlat">
                            <ElOption v-for="item in PlatType"
                                      :key="item.value"
                                      :value="item.value"
                                      :label="item.label"
                            />
                        </ElSelect>
                    </ElFormItem>
                </ElCol>
            </ElRow>

            <div class="info-title">
                <span>企业管理员信息</span>

                <ElButton class="ml20"
                          type="primary"
                          plain
                          round
                          size="small"
                          @click="useLegalInfo"
                >
                    使用法人信息
                </ElButton>
            </div>

            <ElRow :gutter="20">
                <ElCol :span="8">
                    <ElFormItem label="企业管理员账号"
                                prop="enterpriseAccount"
                    >
                        <ElInput v-model="form.enterpriseAccount"
                                 :disabled="true"
                        />
                    </ElFormItem>
                </ElCol>

                <ElCol :span="8">
                    <ElFormItem label="姓名"
                                prop="userName"
                    >
                        <ElInput v-model="form.userName" />
                    </ElFormItem>
                </ElCol>

                <ElCol :span="8">
                    <ElFormItem label="身份证号"
                                prop="idCard"
                    >
                        <ElInput v-model="form.idCard"
                                 maxlength="18"
                        />
                    </ElFormItem>
                </ElCol>
            </ElRow>

            <ElRow :gutter="20">
                <ElCol :span="8">
                    <ElFormItem label="手机号"
                                prop="phonenumber"
                    >
                        <ElInput v-model="form.phonenumber"
                                 maxlength="11"
                        />
                    </ElFormItem>
                </ElCol>

                <ElCol :span="8">
                    <ElFormItem label="邮箱"
                                prop="email"
                    >
                        <ElInput v-model="form.email" />
                    </ElFormItem>
                </ElCol>
            </ElRow>

            <div style="text-align: center;">
                <ElButton type="primary"
                          @click="doSave(formRef)"
                >
                    保存
                </ElButton>

                <ElButton @click="goback">
                    取消
                </ElButton>
            </div>
        </ElForm>
    </ElCard>
</template>

<style lang="less" scoped>
.info-title {
    font-size: 16px;
    font-weight: 600;
    line-height: 60px;
    display: flex;
    align-items: center;
}

.tip_box {
    :deep(.el-form-item__content) {
        display: flex;
        flex-direction: row;
        align-items: flex-end;

        .tips {
            padding-left: 5px;
        }
    }
}
</style>
